package com.universest.swordholder.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.universest.swordholder.aitool.Constants
import com.universest.swordholder.model.config.ConfigItem
import com.universest.swordholder.model.user.UserManager
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

class ConfigScreenViewModel : BaseViewModel(){

    private var _configItems = mutableListOf<ConfigItem>(
        ConfigItem(
            type = "textInput",
            key = "deepseekModelUrl",
            name = "模型地址",
            defaultValue = Constants.DEEPSEEK_API_URL,
            description = "可在此配置大模型地址。"
        ),
        ConfigItem(
            type = "textInput",
            key = "deepseekApiKey",
            name = "API Key",
            defaultValue = "",
            description = "可在此配置大模型API Key。"
        ),
        ConfigItem(
            type = "checkbox",
            key = "deepseekDeepThought",
            name = "深度思考",
            defaultValue = "true",
            description = "可以配置是否开启深度思考功能。"
        ),
    )

    val configItems: List<ConfigItem>
        get() = _configItems

    fun getUserConfig(key: String, defaultValue: String): Flow<String> {
        return UserManager.instance.getUserConfigManager()
            .getConfig(key,defaultValue)
            .map { it ?: defaultValue }
    }

    fun setUserConfig(configItem: ConfigItem, value: String) {
        viewModelScope.launch {
            try {
                UserManager.instance.getUserConfigManager()
                    .saveConfig(configItem.key, value)
            }catch (e: Throwable){
                Log.e("ConfigScreenViewModel", "setUserConfig: ${e.message}")
            }
        }
    }
}